如何获取今年 java 过去几个月的列表?

How to get list of passed months of this year java?

我正在使用 PhilJay/MPAndroidChart android 库中的 SingleLine 图表,我需要一份当年过去月份的列表。例如,从一月到十月,但十月什么时候过去,然后从一月到十一月,依此类推。 我试过这些:计算给定月份的前 12 个月 - SimpleDateFormat 但所有这些都是以前的 12 个月,我想从今年年初开始

@SuppressLint("SimpleDateFormat")
private void handleXAxis() {
    List<String> allDates = new ArrayList<>();
    String maxDate = "Jan";
    SimpleDateFormat monthDate = new SimpleDateFormat("MMM");
    Calendar cal = Calendar.getInstance();
    try {
        cal.setTime(Objects.requireNonNull(monthDate.parse(maxDate)));
    } catch (ParseException e) {
        e.printStackTrace();
    }
    for (int i = 1; i <= 12; i++) {
        String month_name1 = monthDate.format(cal.getTime());
        allDates.add(month_name1);
        cal.add(Calendar.MONTH, -1);
    }
}

tl;dr ⇒ java.time

个月到(包括)当前的 List<YearMonth>:

public static List<YearMonth> getMonthsOfCurrentYear() {
    YearMonth currentMonth = YearMonth.now();
    List<YearMonth> yearMonths = new ArrayList<>();
    
    for (int month = 1; month <= currentMonth.getMonthValue(); month++) {
        yearMonths.add(YearMonth.of(currentMonth.getYear(), month));
    }
    
    return yearMonths;
}

个月到(包括)当前的 List<String>:

public static List<String> getMonthNamesOfCurrentYear() {
    YearMonth currentMonth = YearMonth.now();
    List<String> yearMonths = new ArrayList<>();
    
    for (int month = 1; month <= currentMonth.getMonthValue(); month++) {
        yearMonths.add(YearMonth.of(currentMonth.getYear(), month)
                                .format(DateTimeFormatter.ofPattern("MMM",
                                                                    Locale.ENGLISH)));
    }
    
    return yearMonths;
}

作为替代方案,您可以使用 Month 的显示名称而不是 DateTimeFormatter.ofPattern("MMM")

public static List<String> getMonthNamesOfCurrentYear() {
    YearMonth currentMonth = YearMonth.now();
    List<String> yearMonths = new ArrayList<>();
    
    for (int month = 1; month <= currentMonth.getMonthValue(); month++) {
        yearMonths.add(Month.of(month)
                            .getDisplayName(TextStyle.SHORT, Locale.ENGLISH));
    }
    
    return yearMonths;
}

第二个和第三个例子的输出:

Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct

这样调用时
System.out.println(String.join(", ", getMonthNamesOfCurrentYear()));